/*
 * @Author: fhw
 * @Date: 2022-07-17 15:17:05
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-12-27 11:39:15
 * @Description:
 */
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common'
import { Request, Response } from 'express'
import { equals } from 'ramda'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse<Response>()
    const request = ctx.getRequest<Request>()
    const exceptionRes: any = exception.getResponse()
    const { message } = exceptionRes
    const errorResponse = {
      data: null, // 获取全部的错误信息
      msg: message,
      code: '400', // 自定义code
      url: request.originalUrl, // 错误的url地址
      success: false,
    }
    const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR
    if (equals(status, 401) && equals(message, 'Unauthorized')) {
      errorResponse.msg = '获取token失败'
      errorResponse.code = '401'
    }
    response.status(200)
    response.header('Content-Type', 'application/json; charset=utf-8')
    response.send(errorResponse)
    // response.status(status).json({
    //   status,
    //   timestamp: new Date().toISOString(),
    //   path: request.url,
    //   error,
    //   message,
    //   success,
    // });
  }
}
